﻿@using WebApp.Models
@model IEnumerable<ApplicationUser>
@{
  /**/
  ViewData["Title"] = "租户管理";
  ViewData["PageName"] = "applicationtenant";
  ViewData["Heading"] = "<i class='fal fa-users text-primary'></i>  租户管理";
  ViewData["Category1"] = "系统管理";
  ViewData["PageDescription"] = "";
}
@section HeadBlock {
  <link href="@Fingerprint.Tag("/Content/css/notifications/toastr/toastr.css")" rel="stylesheet" />
  <link href="@Fingerprint.Tag("/Scripts/easyui/themes/insdep/easyui.min.css")" rel="stylesheet" />
  <link href="@Fingerprint.Tag("/Scripts/easyui/themes/insdep/icon.css")" rel="stylesheet" />
  
}

<div class="row">
  <div class="col-lg-12 col-xl-12">
    <div id="panel-1" class="panel">
      <div class="panel-hdr">
        <h2>
          租户管理
        </h2>
        <div class="panel-toolbar">
          <button class="btn btn-panel bg-transparent fs-xl w-auto h-auto rounded-0" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"><i class="fal fa-window-minimize"></i></button>
          <button class="btn btn-panel bg-transparent fs-xl w-auto h-auto rounded-0" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"><i class="fal fa-expand"></i></button>
        </div>

      </div>
      <div class="panel-container show">
        <div class="panel-content py-2 rounded-bottom border-faded border-left-0 border-right-0  text-muted bg-faded bg-subtlelight-fade">
          <div class="row no-gutters align-items-center">
            <div class="col">
              <!-- 开启授权控制请参考 @@if (Html.IsAuthorize("Create") -->
              <div class="btn-group btn-group-sm">
                <button onclick="append()" class="btn btn-default"> <span class="fal fa-plus mr-1"></span> 注册新租户 </button>
              </div>
              <div class="btn-group btn-group-sm">
                <button name="deletebutton" disabled onclick="removeit()" class="btn btn-default"> <span class="fal fa-times mr-1"></span> @Html.L("Delete") </button>
              </div>
              <div class="btn-group btn-group-sm">
                <button name="savebutton" disabled onclick="accept()" class="btn btn-default"> <span class="fal fa-save mr-1"></span> @Html.L("Save") </button>
              </div>
              <div class="btn-group btn-group-sm">
                <button name="cancelbutton" disabled onclick="reject()" class="btn btn-default"> <span class="fal fa-ban mr-1"></span> @Html.L("Cancel") </button>
              </div>
              <div class="btn-group btn-group-sm">
                <button onclick="reload()" class="btn btn-default"> <span class="fal fa-search mr-1"></span> @Html.L("Refresh") </button>
              </div>

            </div>

          </div>

        </div>
        <div class="panel-content">
          <div class="table-responsive">
            <table id="tenant_datagrid"></table>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- END MAIN CONTENT -->

@section ScriptsBlock {


  <script src="@Fingerprint.Tag("/Scripts/notifications/toastr/toastr.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/plugin/jquery.serializejson/jquery.serializejson.min.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/plugin/moment/moment-with-locales.min.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/easyui/jquery.easyui.min.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/easyui/plugins/datagrid-filter.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/jquery.easyui.component.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/jquery.extend.formatter.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/easyui/locale/easyui-lang-zh_CN.js")"></script>
  <script src="@Fingerprint.Tag("/Scripts/jquery.custom.extend.js")"></script>
  <script type="text/javascript">
    var editIndex = undefined;
    var tenant = {};
    function reload() {
      $dg.datagrid('unselectAll');
      $dg.datagrid('uncheckAll');
      $dg.datagrid('reload');

    }

    var $dg = $('#tenant_datagrid');
    //关闭编辑状态
    function endEditing() {
      if (editIndex === undefined) {
        return true;
      }
      if ($dg.datagrid('validateRow', editIndex)) {
        $dg.datagrid('endEdit', editIndex);
        return true;
      } else {
        const invalidinput = $('input.validatebox-invalid', $dg.datagrid('getPanel'));
        const fieldnames = invalidinput.map((index, item) => {
          return $(item).attr('placeholder') || $(item).attr('id');
        });
        $.messager.alert('提示', `${Array.from(fieldnames)} 输入有误.`, 'error');
        return false;
      }
    }
    //提交保存后台数据库
    function accept() {
      if (endEditing()) {
        if ($dg.datagrid('getChanges').length > 0) {
          const inserted = $dg.datagrid('getChanges', 'inserted').map(item => {
            item.TrackingState = 1;
            return item;
          });
          const updated = $dg.datagrid('getChanges', 'updated').map(item => {
            item.TrackingState = 2
            return item;
          });
          const deleted = $dg.datagrid('getChanges', 'deleted').map(item => {
            item.TrackingState = 3
            return item;
          });
          //过滤已删除的重复项
          const changed = inserted.concat(updated.filter(item => {
            return !deleted.includes(item);
          })).concat(deleted);
          //console.table(changed);
          $.messager.progress({ title: '请等待', msg: '正在保存数据...', interval: 200 });
          $.post('/AccountManage/SaveTenantData', { tenant: changed })
            .done(response => {
              $.messager.progress('close');
              //console.log(response);
              if (response.success) {
                toastr.success('保存成功');
                $dg.datagrid('acceptChanges');
                reload();
                hook = false;
              } else {
                $.messager.alert('错误', response.err, 'error');
              }
            })
            .fail((jqXHR, textStatus, errorThrown) => {
              $.messager.progress('close');
              $.messager.alert('异常', `${jqXHR.status}: ${jqXHR.statusText} `, 'error');
            });
        }
      }
    }
    //单击列开启编辑功能
    function onClickCell(index, field) {
      product = $dg.datagrid('getRows')[index];
      const _actions = ['action', 'ck'];
      if (!true || $.inArray(field, _actions) >= 0) {
        return;
      }
      if (editIndex !== index) {
        if (endEditing()) {
          $dg.datagrid('selectRow', index)
            .datagrid('beginEdit', index);
          hook = true;
          editIndex = index;
          const ed = $dg.datagrid('getEditor', { index: index, field: field });
          if (ed) {
            ($(ed.target).data('textbox') ? $(ed.target).textbox('textbox') : $(ed.target)).focus();
          }
        } else {
          $dg.datagrid('selectRow', editIndex);
        }
      }
    }
    function append() {
      tenant = { Disabled:false};
      if (endEditing()) {
        //对必填字段进行默认值初始化
        $dg.datagrid('insertRow',
          {
            index: 0,
            row: tenant
          });
        editIndex = 0;
        $dg.datagrid('selectRow', editIndex)
          .datagrid('beginEdit', editIndex);
        hook = true;
      }
    }
    function removeit() {
      const rows = $dg.datagrid('getChecked');
      if (rows.length > 0) {
        var id = rows.filter(item => item.Id != null).map(item => {
          return item.Id;
        });
        $.messager.confirm('确认', `你确定要删除这 <span class='badge badge-icon position-relative'>${id.length}</span> 行记录?`, result => {
          if (result) {
            $.post('/AccountManage/DeleteCheckeTenant', { id: id })
              .done(response => {
                if (response.success) {
                  toastr.success('删除成功', '确认', { timeOut: 2000 });
                  $dg.datagrid('uncheckAll');
                  $dg.datagrid('reload');
                } else {
                  $.messager.alert('错误', response.err, 'error');
                }
              })
              .fail((jqXHR, textStatus, errorThrown) => {
                //console.log(errorThrown);
                $.messager.alert('失败', errorThrown, 'error');
              });
          }
        });
      } else {
        $.messager.alert('提示', '请选择要删除的租户');

      }
    }
    $(function () {
      $dg.datagrid({
        rownumbers: true,
        checkOnSelect: false,
        selectOnCheck: false,
        idField: 'Id',
        sortName: 'Id',
        sortOrder: 'desc',
        remoteFilter: true,
        singleSelect: false,
        url: '/AccountManage/GetTenantData',
        method: 'get',
        onClickCell: onClickCell,
        pagination: true,
        clientPaging: false,
        striped: true,
        onBeforeLoad: function () {
          const that = $(this);
          document.addEventListener('smartPanel.onFullscreen', () => {
            setTimeout(() => {
              that.datagrid('resize');
            }, 200)
          })
        },
        onLoadSuccess: function (data) {
          editIndex = undefined;
          $("button[name*='deletebutton']").prop('disabled', true);
          $("button[name*='savebutton']").prop('disabled', true);
          $("button[name*='cancelbutton']").prop('disabled', true);
        },
        onCheck: function () {
          $("button[name*='deletebutton']").prop('disabled', false);
        },
        onUncheck: function () {
          const checked = $(this).datagrid('getChecked').length > 0;
          $("button[name*='deletebutton']").prop('disabled', !checked);
        },
        onSelect: function (index, row) {
          product = row;
        },
        onBeginEdit: function (index, row) {
          //const editors = $(this).datagrid('getEditors', index);

        },
        onEndEdit: function (index, row) {

        },
        onBeforeEdit: function (index, row) {
          editIndex = index;
          row.editing = true;
          $("button[name*='deletebutton']").prop('disabled', false);
          $("button[name*='cancelbutton']").prop('disabled', false);
          $("button[name*='savebutton']").prop('disabled', false);
          $(this).datagrid('refreshRow', index);
        },
        onAfterEdit: function (index, row) {
          row.editing = false;
          editIndex = undefined;
          $(this).datagrid('refreshRow', index);
        },
        onCancelEdit: function (index, row) {
          row.editing = false;
          editIndex = undefined;
          $("button[name*='deletebutton']").prop('disabled', true);
          $("button[name*='savebutton']").prop('disabled', true);
          $("button[name*='cancelbutton']").prop('disabled', true);
          $(this).datagrid('refreshRow', index);
        },
        columns: [[
          { field: 'ck', checkbox: true },
          {
            field: 'Name',
            title: '<span class="required">租户名称</span>',
            width: 150,
            sortable: true,
            resizable: true,
            editor: {
              type: 'textbox',
              options: { prompt: '租户名称', required: true, validType: 'length[0,50]' }
            },
          },
          {
            field: 'ConnectionStrings',
            title: '数据库连接',
            width: 320,
            sortable: true,
            resizable: true,
            editor: {
              type: 'textbox',
              options: { prompt: '数据库连接字符串', multiline:true, required: false, validType: 'length[0,500]' }
            },
          },
          {
            field: 'Disabled',
            title: '是否禁用',
            width: 100,
            sortable: true,
            resizable: true,
            formatter: checkboxformatter,
            editor: {
              type: 'checkboxeditor'
            }
          }


        ]]
      });
      $dg.datagrid('enableFilter', [
        {
          field: 'Disabled',
          type: 'booleanfilter'
        }]);
    });
  </script>

}

